package com.asimplefox.configs;

import jakarta.activation.DataSource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Slf4j
@RequiredArgsConstructor
@Component
public class GoogleEmailConfig {

    @Value("${spring.mail.username}")
    private String mailFrom;

    private final JavaMailSender javaMailSender;

    public void sendMailSimple(String to, String subject, String text) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 发件人
        simpleMailMessage.setFrom(mailFrom);
        // 收件人
        simpleMailMessage.setTo(to);
        // 邮件主题
        simpleMailMessage.setSubject(subject);
        // 邮件内容
        simpleMailMessage.setText(text);
        javaMailSender.send(simpleMailMessage);
    }

    public void sendWithAttach(String to, String subject, String text, MailAttachInfoDTO... attachInfos) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailFrom);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text);
            for (MailAttachInfoDTO attachInfo : attachInfos) {
                if (attachInfo == null) continue;
                helper.addAttachment(attachInfo.getAttachName(), attachInfo.getAttachSource());
            }
        } catch (MessagingException e) {
            log.warn("MailSendServiceImpl.sendWithAttach failed.", e);
        }
        javaMailSender.send(message);
    }

    @Getter
    public static class MailAttachInfoDTO {
        private String attachName;
        private DataSource attachSource;
    }
}
